package com.tyqx.detectcputemperaturesendmessage.controller;

import com.tyqx.detectcputemperaturesendmessage.model.DiskModel;
import com.tyqx.detectcputemperaturesendmessage.model.PlotFile;
import com.tyqx.detectcputemperaturesendmessage.util.ExportExcel;
import com.tyqx.detectcputemperaturesendmessage.util.MD5Util;
import com.tyqx.detectcputemperaturesendmessage.util.PrintDirUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RequestMapping("/filter")
@Controller
public class FilterPlotController {

    private static final Logger logger = LoggerFactory.getLogger(FilterPlotController.class);


    @RequestMapping(value = "/filterPlot", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String filterPolt(String filterPoltPath) {
        if (null == filterPoltPath || "".equals(filterPoltPath)) {
            return "请填写过滤的文件夹";
        }
        File dir = new File(filterPoltPath);
        if (!dir.isDirectory()) {
            return "输入的路径是文件或者不存在的目录，请输入正确的目录";
        }
        try {
            PrintDirUtil.filterFile(dir, ".plot");
            List<File> fileList = PrintDirUtil.fileList;
            PrintDirUtil.fileList = new ArrayList<>();
            fileList.sort(new Comparator<File>() {
                @Override
                public int compare(File o1, File o2) {
                    Long o1Leng = o1.length();
                    Long o2Leng = o2.length();
                    return o1Leng.compareTo(o2Leng);
                }
            });

            Long fileLengthTemp = 0L;
            File fileTemp = null;
            String returnStr = "";
            for (int i = 0; i < fileList.size(); i++) {
                if (i == 0) {
                    fileLengthTemp = fileList.get(i).length();
                    fileTemp = fileList.get(i);
                } else {
                    Long fileLength = fileList.get(i).length();
                    File file = fileList.get(i);
                    if (fileLengthTemp == fileLength) {
                        logger.info("文件：" + fileTemp.getAbsolutePath() + "和文件：" + file.getAbsolutePath() + "相等");
                        if ("".equals(returnStr)) {
                            returnStr = returnStr + "文件：" + fileTemp.getAbsolutePath() + "和文件：" + file.getAbsolutePath() + "\t《相等》";
                        } else {
                            returnStr = returnStr + "\n\n\n文件：" + fileTemp.getAbsolutePath() + "和文件：" + file.getAbsolutePath() + "\t《相等》";
                        }
                        String filePath = file.getAbsolutePath();
                        String fileTempPath = fileTemp.getAbsolutePath();
                        String fileHashCode = MD5Util.md5HashCode(filePath);
                        String fileTempHashCode = MD5Util.md5HashCode(fileTempPath);

                        if (fileHashCode.equals(fileTempHashCode)) {
                            returnStr = returnStr + "\n文件：" + fileTemp.getAbsolutePath() + "和文件：" + file.getAbsolutePath() + "\t《hashCode相等》";
                        } else {
                            returnStr = returnStr + "\n文件：" + fileTemp.getAbsolutePath() + "和文件：" + file.getAbsolutePath() + "\t《hashCode不相等》";
                        }
                    }
                    fileLengthTemp = fileLength;
                    fileTemp = file;
                }
            }

            if ("".equals(returnStr)) {
                returnStr = "没有找到有相等的文件";
            }
            return returnStr;

        } catch (Exception e) {
            e.printStackTrace();
            return "发生错误";
        }

    }

    /**
     * @Title DownloadDoctorWork
     * @Description
     * @Date 2018/9/28
     * @Param [map, request, response]
     * @Return org.springframework.http.ResponseEntity<byte [ ]>
     */
    @RequestMapping(value = "/filterPlotPro", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ResponseEntity<byte[]> filterPoltPro(String noFilterPoltPath, HttpServletRequest request, HttpServletResponse response) {
        String returnStr = "";
        List<Map<String, byte[]>> fileByteMapList = new ArrayList<>();
        try {
            List<String> noFilterPoltPathList = new ArrayList<>();
            if (("").equals(noFilterPoltPath) || null == noFilterPoltPath) {
                logger.info("没有需要忽略的磁盘文件，将检索全部磁盘");
            } else {
                String[] noFilterPoltPathArr = noFilterPoltPath.split(",");
                noFilterPoltPathList = Arrays.asList(noFilterPoltPathArr);
            }

            List<String> letterStrList = new ArrayList<>();
            for (int i = 1; i <= 26; i++) {
                char letterChar = (char) (96 + i);
                String letterStr = String.valueOf(letterChar).toUpperCase() + ":";
                if (!letterStr.equals("C:")) {
                    letterStrList.add(letterStr);
                }
            }
            for (int j = 1; j <= 100; j++) {
                String diskDirPathBasic = "C:/EXTRADISK/";
                String diskDirPath = diskDirPathBasic + j;
                letterStrList.add(diskDirPath);
            }
            List<String> diskPathList = PrintDirUtil.compare(noFilterPoltPathList, letterStrList);

            List<DiskModel> diskModelList = new ArrayList<>();

            List<PlotFile> plotFileList = new ArrayList<>();

            Integer totalPlotFileSize = 0;
            for (String diskPath : diskPathList) {
                logger.info("当前遍历的disk：" + diskPath);
                File dir = new File(diskPath);
                if (!dir.isDirectory()) {
                    logger.info(diskPath + "磁盘不存在，跳过检索");
                    continue;
                }
                logger.info("开始检索磁盘:" + diskPath);
                String freeSpace = dir.getFreeSpace() / 1024 / 1024 / 1024 + "G";
                String totalSpace = dir.getTotalSpace() / 1024 / 1024 / 1024 + "G";
                String usableSpace = (dir.getTotalSpace() - dir.getFreeSpace()) / 1024 / 1024 / 1024 + "G";



                try {
                    PrintDirUtil.filterFile(dir, ".plot");
                    List<File> fileList = PrintDirUtil.fileList;
                    PrintDirUtil.fileList = new ArrayList<>();
                    fileList.sort(new Comparator<File>() {
                        @Override
                        public int compare(File o1, File o2) {
                            Long o1Leng = o1.length();
                            Long o2Leng = o2.length();
                            return o1Leng.compareTo(o2Leng);
                        }
                    });
                    totalPlotFileSize = totalPlotFileSize + fileList.size();

                    DiskModel disk = new DiskModel();
                    disk.setDiskName(diskPath);
                    disk.setFreeSpace(freeSpace);
                    disk.setUsableSpace(usableSpace);
                    disk.setTotalSpace(totalSpace);
                    disk.setPlotFileSize(fileList.size());
                    disk.setTotalPlotFileSize(totalPlotFileSize);


                    diskModelList.add(disk);


                    for (int i = 0; i < fileList.size(); i++) {
                        File plotFile = fileList.get(i);
                        String plotFileName = plotFile.getName();
                        String plotFilePath = plotFile.getAbsolutePath();
                        String plotFileHashCode = MD5Util.md5HashCode(plotFilePath);
                        String plotFileSize = plotFile.length() / 1024 / 1024 + "M";

                        PlotFile plotFileModel = new PlotFile();
                        plotFileModel.setPlotFilePath(plotFilePath);
                        plotFileModel.setPlotFileName(plotFileName);
                        plotFileModel.setPlotFileHashCode(plotFileHashCode);
                        plotFileModel.setPlotFileSize(plotFileSize);

                        plotFileList.add(plotFileModel);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (diskModelList.size() > 0) {
                //String excelPath = PrintDirUtil.createExcel(diskModelList,"C:/chiaPlotFile/diskInfo/","磁盘信息");
                //returnStr =  returnStr + "\t" + "磁盘信息Xlsx目录为："+excelPath+"\n\n";
                List<LinkedHashMap<String, Object>> diskMapList = new ArrayList<>();
                for (int i = 0; i < diskModelList.size(); i++) {
                    LinkedHashMap<String, Object> diskMap = new LinkedHashMap<>(diskModelList.size());
                    diskMap.put("value_one", i + 1 + "");
                    diskMap.put("value_two", diskModelList.get(i).getDiskName());
                    diskMap.put("value_three", diskModelList.get(i).getTotalSpace());
                    diskMap.put("value_four", diskModelList.get(i).getFreeSpace());
                    diskMap.put("value_five", diskModelList.get(i).getUsableSpace());
                    diskMap.put("value_six", diskModelList.get(i).getPlotFileSize());
                    diskMap.put("value_seven", diskModelList.get(i).getTotalPlotFileSize());

                    diskMapList.add(diskMap);
                }

                System.out.println("磁盘信息start导出");
                long start = System.currentTimeMillis();
                LinkedHashMap<String, String> titleMap = new LinkedHashMap<>(7);
//此处是自己根据业务场景查询的表单list，根据自己需求改动即可
                List<LinkedHashMap<String, Object>> dataList = diskMapList;
                byte[] filebyte = null;
                titleMap.put("title_one", "序号");
                titleMap.put("title_two", "磁盘名称");
                titleMap.put("title_three", "总空间大小");
                titleMap.put("title_four", "剩余空间大小");
                titleMap.put("title_five", "已用空间大小");
                titleMap.put("title_six", "plot文件数量");
                titleMap.put("title_seven", "plot文件总计");
                try {
                    filebyte = ExportExcel.excelExport(dataList, titleMap, "磁盘信息表", "时间范围：至今", request, response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                long end = System.currentTimeMillis();
                System.out.println("磁盘信息end导出");
                System.out.println("磁盘信息耗时：" + (end - start) + "s");

                Map<String, byte[]> fileMap = new HashMap<>();
                fileMap.put("磁盘信息表.xlsx", filebyte);
//                fileByteList.add(filebyte);
                fileByteMapList.add(fileMap);
            } else {
                returnStr = returnStr + "\t" + "磁盘信息为空，没有下载磁盘信息xlsx";
            }

            if (plotFileList.size() > 0) {
                //String excelPath = PrintDirUtil.createExcel(plotFileList,"C:/chiaPlotFile/plotFileInfo/","plot文件信息");
                //returnStr = returnStr + "\t" + "plot文件信息Xlsx目录为："+excelPath+"\n\n";

                List<LinkedHashMap<String, Object>> diskMapList = new ArrayList<>();
                for (int i = 0; i < plotFileList.size(); i++) {
                    LinkedHashMap<String, Object> diskMap = new LinkedHashMap<>(plotFileList.size());
                    diskMap.put("value_one", i + 1 + "");
                    diskMap.put("value_two", plotFileList.get(i).getPlotFileName());
                    diskMap.put("value_three", plotFileList.get(i).getPlotFilePath());
                    diskMap.put("value_four", plotFileList.get(i).getPlotFileSize());
                    diskMap.put("value_five", plotFileList.get(i).getPlotFileHashCode());

                    diskMapList.add(diskMap);
                }

                System.out.println("plot文件信息start导出");
                long start = System.currentTimeMillis();
                LinkedHashMap<String, String> titleMap = new LinkedHashMap<>(7);
//此处是自己根据业务场景查询的表单list，根据自己需求改动即可
                List<LinkedHashMap<String, Object>> dataList = diskMapList;
                byte[] filebyte = null;
                titleMap.put("title_one", "序号");
                titleMap.put("title_two", "文件名称");
                titleMap.put("title_three", "文件路径");
                titleMap.put("title_four", "文件大小");
                titleMap.put("title_five", "文件哈希");
                try {
                    filebyte = ExportExcel.excelExport(dataList, titleMap, "plot文件信息表", "时间范围：至今", request, response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                long end = System.currentTimeMillis();
                System.out.println("plot文件信息end导出");
                System.out.println("耗时：" + (end - start) + "s");
                Map<String, byte[]> fileMap = new HashMap<>();
                fileMap.put("plot文件信息表.xlsx", filebyte);
//                fileByteList.add(filebyte);
                fileByteMapList.add(fileMap);
            } else {
                returnStr = returnStr + "\t" + "plot文件信息为空，没有下载plot文件信息xlsx";
            }
            // 创建字节数组输出流，用于返回压缩后的输出流字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ZipOutputStream zipOut = new ZipOutputStream(baos);
            for (Map<String, byte[]> fileMapTemp : fileByteMapList) {
                Iterator iter = fileMapTemp.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    Object key = entry.getKey();
                    Object val = entry.getValue();
                    zipOut.putNextEntry(new ZipEntry(key.toString()));
                    zipOut.write((byte[]) val);
                }

            }
            zipOut.close();
            HttpHeaders headers = new HttpHeaders();
            String sheetName = "磁盘信息和plot信息";
            //如果是IE浏览器，则用URLEncode解析
            if (ExportExcel.isMSBrowser(request)) {
                sheetName = URLEncoder.encode(sheetName, "UTF-8");
            } else {//如果是谷歌、火狐则解析为ISO-8859-1
                sheetName = new String(sheetName.getBytes("UTF-8"), "ISO-8859-1");
            }
            //通知浏览器以attachment（下载方式)
            headers.setContentDispositionFormData("attachment", sheetName + ".zip");
            //application/octet-stream二进制流数据（最常见的文件下载）。
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            ResponseEntity<byte[]> filebyte = new ResponseEntity<byte[]>(baos.toByteArray(), headers, HttpStatus.CREATED);
            return filebyte;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
